import {
	defineStore
} from 'pinia';
import {
	toRefs,
	reactive
} from 'vue'
import {
	login
} from '@/api/common.js'

// import {
// 	getAgentMultilevelList,
// 	queryFCustAddressByCustId,
// 	findSysDictDetailByType
// } from '@/api/common.js'

export default defineStore('user', () => {
	const state = reactive({
		userData: uni.getStorageSync('userData') || {}, //包含 agentId，userName,userId等
		token: uni.getStorageSync('token') || '',
		agentList: uni.getStorageSync('agentList') || [],
	});

	if (!state.token) {
		uni.redirectTo({
			url: '/pages/login/login'
		})
	}

	const doLogin = (formData) => {
		return login(formData).then(({
			obj,
			returnCode
		}) => {
			if (returnCode === 'Y') {
				uni.setStorageSync('token', obj.token)
				uni.setStorageSync('userData', obj.author)
				uni.setStorageSync('agentList', obj.agentList)
				state.userData = obj.author
				state.token = obj.token
				state.agentList = obj.agentList
				uni.redirectTo({
					url: '/pages/agentList/agentList'
				});
			}
		})
	}

	const setAgentId = async (agentId) => {
		await uni.setStorageSync('_agentId', agentId)
	}

	return {
		...toRefs(state),
		doLogin,
		setAgentId
	}
})

// 使用
// <script setup>
// import { storeToRefs } from 'pinia'
// const store = useCounterStore()
// // `name` 和 `doubleCount` 是响应式的 ref
// // 同时通过插件添加的属性也会被提取为 ref
// // 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
// const { count, doubleCount } = storeToRefs(store)
// // 作为 action 的 increment 可以直接解构
// const { increment } = store
// </script>